const fs = require('fs')
const path = require('path')


/**
 * 读取路径信息
 * @param {string} path 路径
 */
function getStat(path) {
    return new Promise((resolve, reject) => {
        fs.stat(path, (err, stats) => {
            if (err) {
                resolve(false);
            } else {
                resolve(stats);
            }
        })
    })
}

/**
 * 创建路径
 * @param {string} dir 路径
 */
function mkdir(dir) {
    return new Promise((resolve, reject) => {
        fs.mkdir(dir, err => {
            if (err) {
                resolve(false);
            } else {
                resolve(true);
            }
        })
    })
}

/**
 * 路径是否存在，不存在则创建
 * @param {string} dir 路径
 */
async function dirExists(dir) {
    let isExists = await getStat(dir);
    //如果该路径且不是文件，返回true
    if (isExists && isExists.isDirectory()) {
        return true;
    } else if (isExists) {     //如果该路径存在但是文件，返回false
        return false;
    }

    console.log(dir)
    //如果该路径不存在
    let tempDir = path.parse(dir).dir;      //拿到上级路径
    //递归判断，如果上级目录也不存在，则会代码会在此处继续循环执行，直到目录存在
    let status = await dirExists(tempDir);
    let mkdirStatus;
    if (status) {
        mkdirStatus = await mkdir(dir);
    }
    return mkdirStatus;
}

const serviceFiles = [
    "service_install.bat",
    "service_start.bat",
    "service_stop.bat",
    "service_uninstall.bat",
    "WinSW-x64.exe",
    "WinSW-x64.xml"
]

async function fn() {
    let distPath = process.cwd() + "/build/Release/";
    let distSqlitePath = process.cwd() + "/build/Release/database/";
    await dirExists(distPath);
    await dirExists(distSqlitePath);

    let publicPath = process.cwd() + "/public/";
    let publicDist = process.cwd() + "/build/Release/public/";
    // 复制文件夹
    fs.cp(publicPath, publicDist,
        { recursive: true },
        err => {
            if (err) {
                throw err;
            }
        })

    let sqlitePath = process.cwd() + "/database/sqlite.db";
    let sqliteDist = process.cwd() + "/build/Release/database/sqlite.db";
    // 复制数据库
    fs.copyFile(sqlitePath, sqliteDist,
        err => {
            if (err) {
                throw err;
            }
        })

    // 复制服务器动文件
    serviceFiles.forEach((asset) => {
        let servicePath = process.cwd() + "/build/" + asset;
        let serviceDistPath = process.cwd() + "/build/Release/" + asset;
        fs.copyFile(servicePath, serviceDistPath,
            err => {
                if (err) {
                    throw err;
                }
            })
    })


    console.log('copy base project files complete')
}

fn()